//
//  YYEOAuthViewController.swift
//  weibo14
//
//  Created by mac on 16/3/4.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD


//App Key：
//295758514
//App Secret：
//e50e75c1d6de23b9385c75d676669e32
// appkey
let WB_APPKEY = "295758514"
// 点击授权之后跳转的页面
let WB_REDIRECT_URI = "http://yangye.com"

//http://yangye.com

let WB_APPSECRET = "e50e75c1d6de23b9385c75d676669e32"

class YYEOAuthViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }

    //private lazy var url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)")
private lazy var url =  NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)")
    
    
    override func loadView() {
        super.loadView()
        
        view = webView
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
    
    
    func setupUI() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "back")
        
         navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填写", target: self, action: "autoClick")
        
        navigationItem.title = "新浪微博"
    }
    
    
    @objc private func bakc() {
       
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoClick() {
        
        
        let jsString = "document.getElementById('userId').value='18232531325';document.getElementById('passwd').value='15031212510'"
        // 让当前 webView执行以上这句js代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    // MARK: 懒加载控件
    
    private lazy var webView: UIWebView = {
    
        let vc = UIWebView()
        vc.bounds = self.view.bounds
        vc.delegate = self
        return vc
    }()
    
    
}

extension YYEOAuthViewController:UIWebViewDelegate {

    // 当改变url的时候回询问这个  从而获取token的值
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 判断时候为空 
        guard let requestUrl = request.URL else {
            
            return true
        }
        
        // 转成String
        let urlStr = requestUrl.absoluteString
        
        /*
        if urlStr.hasPrefix(WB_REDIRECT_URI)  {
            // 截取urlStr中 code= 后面的 32位字符
            let query = url.query!
            // 截取 code
            let code = query.substringFromIndex("code=".endIndex)
            // 拿着授权code去获取AccessToken
            print(code)
            HMUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, callback: { (isSuccess) -> () in
                if isSuccess {
        */
        if urlStr.hasPrefix(WB_REDIRECT_URI) {
        
            let query = requestUrl.query!
            
            let code = query.substringFromIndex("code=".endIndex)
            // 拿到授权码
            // dfa1e871cac8eb484cb68ad5b9a997b8
            print("授权吗\(code)")
            
            YYEUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, callBack: { (issucceed) -> () in
                
                if issucceed {
                
                    // 把自己干掉 再去切换控制器  节约内存
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        // 发送通知 统一切换
                        print("登录成功,跳转界面,跳转到欢迎页面里面去,切换根控制器")
                        NSNotificationCenter.defaultCenter().postNotificationName(YYESwitchRootVCNotification, object: self)
                        
                    })
                    
                
                } else {
                
                SVProgressHUD.showErrorWithStatus("请求失败")
                }
                
            })
            

            return false
        }
        
        
      return true
    }
}
